package henu.action;

import henu.bean.ManagePerson;
import henu.bean.PInformation;
import henu.dao.factory.DaoFactory;
import henu.util.AJAX;
import henu.util.CONSTANTS;
import henu.util.Page;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PInformationAction extends ActionSupport {
	private PInformation p=new PInformation();
	private File photo; //上传的文件
    private String photoFileName; //文件名称
    private String url;//转发地址
    private String message;//提示消息
    
    //查询条件
    private String property="-1";
    private String key="-1";
    private String sort;
    private int start;
    private int end;
    
    //接收所有数据
    private List<PInformation> list=null;
 // 分页排序
 	private Page page = new Page();
 	private int pageNum = 1;
 	private int numPerPage = 10;
 	private String orderField = "idcard";
 	private String orderDirection = "asc";
 	private String args;//接收idcard用于删除
 	//用于查询
 	private String idCard="";
 	private String phone="";
 
 	//用于用户信息界面显示单独从公司表中查询到的公司名
 	private String company;
 	//用于后台修改用户的审核状态
 	private String paudit;
 	
 	
	public String getPaudit() {
		return paudit;
	}

	public void setPaudit(String paudit) {
		this.paudit = paudit;
	}
public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}
	
	AJAX ajax;
	public AJAX getAjax() {
		return ajax;
	}
	
	public List<PInformation> getList() {
		return list;
	}
	public void setList(List<PInformation> list) {
		this.list = list;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getNumPerPage() {
		return numPerPage;
	}
	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}
	public String getOrderField() {
		return orderField;
	}
	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}
	public String getOrderDirection() {
		return orderDirection;
	}
	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}
	public String getArgs() {
		return args;
	}
	public void setArgs(String args) {
		this.args = args;
	}
	public String getProperty() {
		return property;
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getEnd() {
		return end;
	}
	public void setEnd(int end) {
		this.end = end;
	}
	public File getPhoto() {
		return photo;
	}
	public void setPhoto(File photo) {
		this.photo = photo;
	}
	public String getPhotoFileName() {
		return photoFileName;
	}
	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}
	public PInformation getP() {
		return p;
	}
	public void setP(PInformation p) {
		this.p = p;
	}
	public String getUrl() {
		return url;
	}
	
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	/*注册一个用户*/
	
	public String register() throws Exception{
		//判断数据库中有没有该用户
		PInformation pFromDb=DaoFactory.getPInformationDaoInstance().findByIdCardOrPhone(p.getIdCard(), p.getPhone());
		if(pFromDb!=null){
			message="你的身份已被占用，<a href='/aqjy/public/register.jsp'>点我重新注册</a>";
		}else{
			//存文件
			String realPath=ServletActionContext.getRequest().getRealPath("/upload/personImages");
			InputStream in=new FileInputStream(photo);
			String fileType=photoFileName.substring(photoFileName.lastIndexOf("."));//截取后缀
			String fileName=p.getPhone()+fileType;//文件名为手机号+后缀
			FileOutputStream out=new FileOutputStream(realPath+"\\"+fileName);
			byte[] buffer=new byte[1024];
			int len=0;
			while((len=in.read(buffer))>0){
				out.write(buffer, 0, len);
			}
			out.close();
			in.close();
			p.setPhotoPath("upload/personImages/"+fileName);
			
			//默认审核未通过
			p.setPaudit("否");
			p.setRegTime(new Date().toLocaleString());
			int result=DaoFactory.getPInformationDaoInstance().add(p);
			
			if(result==0){
				message="注册失败，请重现注册，<a href='/aqjy/public/register.jsp'>点我重新注册</a>";
			}else{
				message="注册成功，等待管理员审核通过后进行登录";
			}
		}
		url="/public/message.jsp";
		return SUCCESS;
	}
	/*
	 * 修改密码
	 */
	public String resetPassword() throws Exception{
		//判断数据库中有没有该用户
		PInformation pFromDb=DaoFactory.getPInformationDaoInstance().findByIdCardAndQuestionAndAnswer(p.getIdCard(), p.getQuestion(), p.getAnswer());
		if(pFromDb==null){
			message="您所填的信息有错误，<a href='/aqjy/public/resetPassword.jsp'>点我重新设置密码</a>";
		}else{
			int result=DaoFactory.getPInformationDaoInstance().resetPassword(p.getIdCard(), p.getPassword());
			if(result==0){
				message="修改失败，<a href='/aqjy/public/resetPassword.jsp'>点我返回设置密码页面 </a>";
			}else{
				message="修改成功，<a href='/aqjy/index.jsp'>点我返回首页 </a>";
			}
		}
		url="/public/message.jsp";
		return SUCCESS;
	}
	/*
	 * 登录
	 */
	public String login() throws Exception{
		//判断数据库中有没有该用户
		PInformation pFromDb=DaoFactory.getPInformationDaoInstance().login(p.getPhone(), p.getPassword());
		if(pFromDb==null){
			ServletActionContext.getRequest().getSession().setAttribute("message", "用户不存在，<a href='/aqjy/public/register.jsp'>点我注册</a>");
			url="/public/message.jsp";
		}else if(pFromDb!=null&&pFromDb.getPaudit().equals("否")){
			ServletActionContext.getRequest().getSession().setAttribute("message","您的审核还没有通过,请耐心等待，<a href='/aqjy/index.jsp'>点我返回首页 </a>");
			url="/public/message.jsp";
		}
		else if(pFromDb!=null&&pFromDb.getPaudit().equals("禁用")){
			ServletActionContext.getRequest().getSession().setAttribute("message","您已被禁用。<a href='/aqjy/index.jsp'>点我返回首页 </a>");
			url="/public/message.jsp";
		}else{
			DaoFactory.getPInformationDaoInstance().updateLastTime(pFromDb.getIdCard());
			ServletActionContext.getRequest().getSession().setAttribute(CONSTANTS.SESSION_PERSON, pFromDb);
			url="/front/index.jsp";
		}
		return SUCCESS;
	}
	//前台用户信息查看
		public String findByUseridCard(){
			PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p1!=null){
				company=DaoFactory.getPInformationDaoInstance().findByComid(p1.getComid());
				p=DaoFactory.getPInformationDaoInstance().findByidCard(p1.getIdCard());	
			//	System.out.println(p1.getIdCard());
				url = "/front/pinformationMessageOrEdit.jsp";
				
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
				
			}
			return SUCCESS;
		}
	//用于前台用户跳转到编辑页面
		public String jump(){
			/*PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			 * ajax = new AJAX();
				ajax.setCallbackType("forward");
				//ajax.setStatusCode("200");
				ajax.setMessage("");
				ajax.setForwardUrl("/aqjy/front/pinformationMessageEdit.jsp");
				url="/admin/ajax.jsp";*/	
			
			PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p1!=null){
			
			//company=DaoFactory.getPInformationDaoInstance().findByComid(p1.getComid());
			p=DaoFactory.getPInformationDaoInstance().findByidCard(p1.getIdCard());
			url="/front/pinformationMessageEdit.jsp";
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
				
			}
			return SUCCESS;
		   
		}
	//前台用户修改信息
		public String update() throws IOException{
			
			PInformation p1=(PInformation) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_PERSON);
			if(p1!=null){
				/*//重置为用户所选改公司的comid
				int comid = DaoFactory.getPInformationDaoInstance().findByCompanyName(company);
				p.setComid(comid);*/
				String realPath=ServletActionContext.getRequest().getRealPath("/upload/personImages");
				InputStream in=new FileInputStream(photo);
				
				String fileType=photoFileName.substring(photoFileName.lastIndexOf("."));//截取后缀
				String fileName=p.getPhone()+fileType;//文件名为手机号+后缀
				FileOutputStream out=new FileOutputStream(realPath+"\\"+fileName);
				byte[] buffer=new byte[1024];
				int len=0;
				while((len=in.read(buffer))>0){
					out.write(buffer, 0, len);
				}
				out.close();
				in.close();
				p.setPhotoPath("upload/personImages/"+fileName);
				//默认审核未通过
				p.setPaudit("否");
				p.setRegTime(new Date().toLocaleString());
				
				int result=DaoFactory.getPInformationDaoInstance().update(p,p1.getIdCard());
				
				
				ajax = new AJAX();
				if (result > 0) {
					ServletActionContext.getRequest().getSession().removeAttribute(CONSTANTS.SESSION_PERSON);
					//PInformation pFromDB=DaoFactory.getPInformationDaoInstance().findByidCard(p1.getIdCard());
					//ServletActionContext.getRequest().getSession().setAttribute(CONSTANTS.SESSION_PERSON, pFromDB);
					ajax.setStatusCode("200");
					ajax.setMessage("更新成功，请在审核通过后登录");
				} else {
					
				}
				url="/front/ajax.jsp";
			}
			else{
				ajax=new AJAX();
				ajax.setMessage("您已离开，重新请登录！");
				ajax.setStatusCode("300");
				url = "/admin/ajax.jsp";
				
			}
			return SUCCESS;
		}
	/*
	 * 退出
	 */
	
	public String exit() throws Exception{
		ServletActionContext.getRequest().getSession().removeAttribute(CONSTANTS.SESSION_PERSON);
		url="/index.jsp";
		return SUCCESS;
	}
	
	//============后台调用==========//
	//查看所有已审核用户
	public String all(){
		ManagePerson m=(ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "qid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		//System.out.println("action查询的关键字是:" + key);
		//System.out.println("查询的依据:" + property);
		page.setProperties2("pinformation",pageNum,numPerPage,property.trim(), key.trim(),"paudit","是","comid",Integer.toString(m.getComid()));
		// 给page这个class设置属性
		list = DaoFactory.getPInformationDaoInstance().findByProperty(
				property.trim(), key.trim(),Integer.toString(m.getComid()),orderDirection.trim(), page.getStart(), page.getEnd());
		url = "/admin/pinformationMessage.jsp";
		return SUCCESS;
	}
	//查看所有待审核用户
	public String findWaitCheck(){
		ManagePerson m=(ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "qid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		page.setProperties2("pinformation",pageNum,numPerPage,property.trim(), key.trim(),"paudit","否","comid",Integer.toString(m.getComid()));
		list = DaoFactory.getPInformationDaoInstance().findWaitChkeck(
				property.trim(), key.trim(),Integer.toString(m.getComid()),orderDirection.trim(), page.getStart(), page.getEnd());
		url = "/admin/pinformationWaitCheck.jsp";
		return SUCCESS;
	}
	//删除已审核的单个用户
	public String deleteByIdCardChecked(){
	
		
		int result = DaoFactory.getPInformationDaoInstance().deleteByIdCard(args);
		if (result > 0) {
			HandleMsg("200", "删除成功！", "userAll","");
		} else {
			HandleMsg("300", "删除失败！", "","");
		}
		return SUCCESS;
		
	}
	//删除未审核的单个用户
		public String deleteByIdCardWithoutCheck(){
		
			
			int result = DaoFactory.getPInformationDaoInstance().deleteByIdCard(args);
			if (result > 0) {
				HandleMsg("200", "删除成功！", "userWaitCheck","");
			} else {
				HandleMsg("300", "删除失败！", "","");
			}
			return SUCCESS;
			
		}
	
	//用于查看已审核(或待审核)并跳转到单个用户
	public String findByidCard(){
		
		p=DaoFactory.getPInformationDaoInstance().findByidCard(args);
		url = "/admin/pinformationToCheck.jsp";
		return SUCCESS;
	}
	//后台审核通过、不通过、禁用、启用、单个用户并添加备注
	public String pass(){
		//获取司机的备注
		String memo1=ServletActionContext.getRequest().getParameter("memo1");
		int result=DaoFactory.getPInformationDaoInstance().pass(args,memo1,paudit);
		if(result>0){
			HandleMsg("200", "审核或禁用通过", "userAll", "closeCurrent");
			}
		else{
			HandleMsg("300", "审核或禁用失败，请重新操作", "userAll", "");
			}	
		return SUCCESS;
	}
	//后台查看所有的禁用用户
	public String ban(){
		ManagePerson m=(ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "qid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		page.setProperties2("pinformation",pageNum,numPerPage,property.trim(), key.trim(),"paudit","禁用","comid",Integer.toString(m.getComid())); 
		list=DaoFactory.getPInformationDaoInstance().ban(property.trim(), key.trim(),Integer.toString(m.getComid()) ,orderDirection.trim(), page.getStart(), page.getEnd());
		url="/admin/pinformationBan.jsp";
		return SUCCESS;
	}
	public void HandleMsg(String statusCode, String msg, String tabid,String callback) {
		ajax= new AJAX();
		ajax.setCallbackType(callback);
		ajax.setMessage(msg);
		ajax.setStatusCode(statusCode);
		ajax.setNavTabId(tabid);
		url = "/admin/ajax.jsp";
	}
}
